package cn.liuhulu.data;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
import java.util.Scanner;

import cn.liuhulu.entity.Product;
import cn.liuhulu.tool.Tools;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * 数据操作
 * 
 * @author liula
 *
 */
public class Datas {

	/**
	 * 数据文件目录
	 */
	public final static String FILE_PATH = System.getProperty("user.dir") + File.separator + "product.txt";

	/**
	 * 同步数据到本地->写文件
	 * 
	 * @return
	 */
	public static boolean syncDataToLoad(ObservableList<Product> products ) {
		Optional<File> fileOpt = fileRest();
		if (fileOpt.isPresent()) { // 备份历史文件
			File cacheFile = new File(FILE_PATH + "." + Tools.dateRestFormat(null));
			if(cacheFile.exists()) { // 如果缓存文件存在则进行删除
				cacheFile.delete();
			}
			fileOpt.get().renameTo(cacheFile);
		}
		fileOpt = fileRest();
		if (fileOpt.isPresent()) {
			try (PrintWriter fp = new PrintWriter(fileOpt.get())) {
				products.forEach(i -> fp.write(i.toString()+"\n"));
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	private static Optional<File> fileRest() {
		File file = new File(FILE_PATH);
		if (file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return Optional.empty();
			}
		}
		return Optional.of(file);
	}

	/**
	 * 同步数据到应用->读文件
	 * 
	 * @return
	 */
	public static ObservableList<Product> syncDataToApp() {
		ObservableList<Product> products = FXCollections.observableArrayList();
		Optional<File> fileOpt = fileRest();
		if (fileOpt.isPresent()) {
			try (Scanner sc = new Scanner(fileOpt.get())) {
				while (sc.hasNextLine()) {
					String[] names = sc.nextLine().split(",");
					if (names.length >= 2) {
						// 数据格式->名称,规格,价格
						products.add(new Product(names[0], names[1], names[2]));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return products;
	}

}
